package org.gruposp2p.proyectokarma.service

import org.gruposp2p.proyectokarma.domain.CometdMessage;
import org.gruposp2p.proyectokarma.domain.Peer;
import grails.converters.JSON;

class CometdMessageService implements org.gruposp2p.cometd.CometdMessageService {

    boolean transactional = false

    public CometdMessage getCometdMessageFromJSON (String jsonString) {
        def data = JSON.parse(JSON.parse(jsonString).data)
        log.debug "data: " + data
        Peer peerTo, peerFrom
        if (data.peerFrom) peerFrom = Peer.findByPeerid(data.peerFrom);
        if (data.peerTo) peerTo = Peer.findByPeerid(data.peerTo);
        CometdMessage cometdMessage = new CometdMessage(area:data.area ,
            peerFrom:peerFrom , peerTo:peerTo, password:data.password,
            action:data.action, content:data.content, subject:data.subject,
            channel:data.channel, date:new Date())
        return cometdMessage;
    }

    public String getJSONFromCometdMessage (CometdMessage cometdMessage) {
        return [area:cometdMessage.area , peerFrom:cometdMessage.peerFrom ,
            peerTo:cometdMessage.peerTo, password:cometdMessage.password,
            action:cometdMessage.action, content:cometdMessage.content,
            subject:cometdMessage.subject, channel:cometdMessage.channel,
            date:cometdMessage.date]
    }

}

